layui.config({
    base: basePath,
    version: skyeyeVersion
}).extend({
    window: 'js/winui.window'
}).define(['window', 'jquery', 'winui', 'form', 'laydate', 'layer', 'table', 'element'], function (exports) {
    winui.renderColor();
    var $ = layui.$,
        form = layui.form,
        laydate = layui.laydate,
        layer = layui.layer;

    // 获取URL参数
    var params = getUrlParams();
    var workshopId = params.workshopId || '';
    var scheduleId = params.id || '';
    var isEdit = params.isEdit === 'true';

    // 全局变量
    var shiftList = [];
    var employeeList = [];
    var filteredEmployees = [];
    var scheduleData = [];
    var selectedShiftTimeMation = [];
    var weekDays = [];
    var timeSlots = [];
    var startDate = '';
    var endDate = '';
    var shiftId = ''; // 添加shiftId全局变量

    // 初始化函数
    function init() {
        // 获取URL参数
        var urlParams = new URLSearchParams(window.location.search);
        isEdit = urlParams.get('isEdit') === 'true';
        scheduleId = urlParams.get('id');
        workshopId = urlParams.get('workshopId');

        // 初始化日期选择器
        initDatePickers();

        // 初始化表单事件
        initFormEvents();

        // 添加直接的事件监听，确保能捕获到班次变化
        $('#shiftSelect').on('change', function () {
            var selectedShiftId = $(this).val();
            if (selectedShiftId) {
                handleShiftChange(selectedShiftId);
            } else {
                selectedShiftTimeMation = [];
                displayShiftTimesInfo();
                renderScheduleTable();
            }
        });

        // 如果是编辑模式，先获取排班详情
        if (isEdit && scheduleId) {
            fetchScheduleDetail();
        } else {
            // 获取车间数据
            fetchWorkShop();
        }

        // 初始化拖放功能
        initDragAndDrop();

        // 初始化班次时间段信息区域
        displayShiftTimesInfo();

        // 添加全局鼠标悬浮事件处理
        setupHoverEvents();
    }

    // 设置鼠标悬浮事件
    function setupHoverEvents() {
        // 先移除所有现有的事件处理程序
        $(document).off('mouseenter mouseleave mousemove', '.work-station-info');
        $(document).off('click', '.already-scheduled');
        $('.employee-hover-tooltip').remove();

        // 使用事件委托，为所有工位添加鼠标悬浮事件
        $(document).on('mouseenter', '.work-station-info', function (e) {
            var $workstation = $(this);
            var workstationEmployees = $workstation.data('employees') || [];

            if (workstationEmployees.length > 0) {
                // 移除现有tooltip
                $('.employee-hover-tooltip').remove();

                // 创建员工名字列表
                var tooltipContent = '<div class="employee-hover-tooltip">';
                tooltipContent += '<div class="tooltip-title">已排班员工列表</div>';
                workstationEmployees.forEach(function (emp) {
                    var employeeName = emp.employeeName || emp.staffName || emp.name || '未知员工';
                    var jobNumber = emp.jobNumber || (emp.staffMation && emp.staffMation.jobNumber) || '';

                    tooltipContent += '<div class="tooltip-employee-item">';
                    tooltipContent += '<div class="employee-info">';
                    tooltipContent += '<span class="employee-name">' + employeeName + '</span>';
                    tooltipContent += '<span class="employee-number">工号：' + jobNumber + '</span>';
                    tooltipContent += '</div>';
                    tooltipContent += '<span class="remove-employee" data-employee-id="' + (emp.employeeId || emp.staffId) +
                        '" data-date="' + $workstation.data('date') +
                        '" data-workstation-id="' + $workstation.data('work-id') + '">×</span>';
                    tooltipContent += '</div>';
                });
                tooltipContent += '</div>';

                // 添加到页面
                var $tooltip = $(tooltipContent);
                $('body').append($tooltip);

                // 计算tooltip位置
                var workstationOffset = $workstation.offset();
                var workstationWidth = $workstation.outerWidth();
                var workstationHeight = $workstation.outerHeight();
                var tooltipWidth = $tooltip.outerWidth();
                var windowWidth = $(window).width();
                var windowHeight = $(window).height();
                var scrollTop = $(window).scrollTop();

                // 默认显示在工位的右侧
                var left = workstationOffset.left + workstationWidth + 10;
                var top = workstationOffset.top;

                // 如果右侧空间不够，则显示在左侧
                if (left + tooltipWidth > windowWidth) {
                    left = workstationOffset.left - tooltipWidth - 10;
                }

                // 确保tooltip不会超出窗口底部
                if (top + $tooltip.outerHeight() > windowHeight + scrollTop) {
                    top = windowHeight + scrollTop - $tooltip.outerHeight() - 10;
                }

                // 设置tooltip位置
                $tooltip.css({
                    top: top,
                    left: left
                });

                // 显示已排班按钮
                $workstation.find('.already-scheduled').show().text('已排员工: ' + workstationEmployees.length);

                // 添加移除员工的点击事件
                $('.remove-employee').on('click', function (e) {
                    e.stopPropagation();
                    var employeeId = $(this).data('employee-id');
                    var date = $(this).data('date');
                    var workstationId = $(this).data('workstation-id');

                    // 找到当前时间段
                    var currentSchedule = scheduleData.find(function (schedule) {
                        return schedule.employeeId === employeeId &&
                            schedule.date === date &&
                            schedule.workstationId === workstationId;
                    });

                    if (currentSchedule) {
                        // 获取当前时间段的ID
                        var timeSlotId = currentSchedule.timeSlotId;
                        var startTime = currentSchedule.startTime;
                        var endTime = currentSchedule.endTime;

                        // 从scheduleData中移除该员工在整周相同时间段的所有排班记录
                        scheduleData = scheduleData.filter(function (schedule) {
                            // 如果是同一个员工、同一个工位、同一个时间段，则移除
                            var isSameEmployee = schedule.employeeId === employeeId;
                            var isSameWorkstation = schedule.workstationId === workstationId;
                            var isSameTimeSlot = schedule.timeSlotId === timeSlotId &&
                                schedule.startTime === startTime &&
                                schedule.endTime === endTime;

                            // 保留不满足以上所有条件的记录
                            return !(isSameEmployee && isSameWorkstation && isSameTimeSlot);
                        });

                        // 重新渲染排班表
                        renderScheduleTable();

                        // 关闭tooltip
                        $('.employee-hover-tooltip').remove();

                        // 显示提示消息
                        layer.msg('已移除该员工本周此时间段的所有排班', { icon: 1 });
                    }
                });
            }
        });

        // 当鼠标离开工位和tooltip时关闭tooltip
        $(document).on('mouseleave', '.work-station-info, .employee-hover-tooltip', function (e) {
            var $tooltip = $('.employee-hover-tooltip');
            var $workstation = $('.work-station-info:hover');
            var relatedTarget = e.relatedTarget;

            // 检查鼠标是否移动到tooltip或工位上
            if (!$(relatedTarget).closest('.employee-hover-tooltip').length &&
                !$(relatedTarget).closest('.work-station-info').length) {
                $tooltip.remove();

                // 如果没有员工，隐藏已排班按钮
                var $currentWorkstation = $(this);
                if ($currentWorkstation.hasClass('work-station-info')) {
                    var workstationEmployees = $currentWorkstation.data('employees') || [];
                    if (workstationEmployees.length === 0) {
                        $currentWorkstation.find('.already-scheduled').hide();
                    }
                }
            }
        });

        // 移除mousemove事件，因为我们不再需要tooltip跟随鼠标
    }

    // 初始化日期选择器
    function initDatePickers() {
        // 获取当前日期
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var day = now.getDate();

        // 格式化日期
        var formattedMonth = month < 10 ? '0' + month : month;
        var formattedDay = day < 10 ? '0' + day : day;

        // 设置默认日期范围（当前日期开始，一周后结束）
        startDate = year + '-' + formattedMonth + '-' + formattedDay;

        // 计算一周后的日期
        var nextWeek = new Date(now);
        nextWeek.setDate(nextWeek.getDate() + 6);
        var nextYear = nextWeek.getFullYear();
        var nextMonth = nextWeek.getMonth() + 1;
        var nextDay = nextWeek.getDate();

        // 格式化日期
        var formattedNextMonth = nextMonth < 10 ? '0' + nextMonth : nextMonth;
        var formattedNextDay = nextDay < 10 ? '0' + nextDay : nextDay;

        endDate = nextYear + '-' + formattedNextMonth + '-' + formattedNextDay;

        // 初始化开始日期选择器
        laydate.render({
            elem: '#startDate',
            value: startDate,
            done: function (value) {
                startDate = value;
                renderScheduleTable();
            }
        });

        // 初始化结束日期选择器
        laydate.render({
            elem: '#endDate',
            value: endDate,
            done: function (value) {
                endDate = value;
                renderScheduleTable();
            }
        });
    }

    // 自动排班功能
    function autoSchedule() {
        // 检查是否选择了班次
        if (!shiftId) {
            layer.msg('请先选择班次', { icon: 0 });
            return;
        }

        // 确保已选择班次的时间段
        if (!selectedShiftTimeMation || selectedShiftTimeMation.length === 0) {
            layer.msg('当前班次没有时间段信息，请选择其他班次', { icon: 0 });
            return;
        }

        // 获取日期范围
        var startDateStr = $('#startDate').val();
        var endDateStr = $('#endDate').val();

        // 收集所有员工ID
        var employeeIds = employeeList.map(function (employee) {
            return {
                id: employee.staffId || employee.id,
                weight: "100" // 默认权重
            };
        });

        if (employeeIds.length === 0) {
            layer.msg('没有可用的员工进行排班', { icon: 0 });
            return;
        }

        // 收集所有时间段ID
        var timeSlotIds = selectedShiftTimeMation.map(function (timeSlot) {
            return timeSlot.id;
        }).filter(Boolean);

        if (timeSlotIds.length === 0) {
            layer.msg('当前班次没有有效的时间段ID', { icon: 0 });
            return;
        }

        // 收集所有工位ID
        var workstationIds = [];
        selectedShiftTimeMation.forEach(function (timeSlot) {
            if (timeSlot.shiftsTimeWorkMation) {
                var workMations = [];

                if (typeof timeSlot.shiftsTimeWorkMation === 'string') {
                    try {
                        workMations = JSON.parse(timeSlot.shiftsTimeWorkMation);
                    } catch (e) {
                        workMations = [];
                    }
                } else if (Array.isArray(timeSlot.shiftsTimeWorkMation)) {
                    workMations = timeSlot.shiftsTimeWorkMation;
                }

                workMations.forEach(function (workstation) {
                    workstationIds.push(workstation.id);
                });
            }
        });

        // 如果没有从班次时间段获取到工位，则使用工位列表
        if (workstationIds.length === 0 && workstationList.length > 0) {
            workstationIds = workstationList.map(function (ws) {
                return ws.id;
            });
        }

        if (workstationIds.length === 0) {
            layer.msg('当前班次没有有效的工位信息', { icon: 0 });
            return;
        }

        // 构建请求参数
        var params = {
            farmId: workshopId,
            schedulingShiftsId: shiftId,
            employeeIds: JSON.stringify(employeeIds),
            schedulingShiftsTimeIds: timeSlotIds.join(','),
            schedulingShiftsTimeWorkId: workstationIds.join(','),
            startTime: startDateStr + ' 00:00',
            endTime: endDateStr + ' 23:59'
        };

        // 显示加载提示
        layer.load(2);

        // 发送请求
        AjaxPostUtil.request({
            url: sysMainMation.checkworkBasePath + 'autoComputeScheduling',
            params: params,
            type: 'json',
            method: "POST",
            callback: function (json) {
                layer.closeAll('loading');

                if (json.returnCode === 0) {
                    // 处理返回的排班数据
                    if (json.bean && json.bean.schedulingTimeMation) {
                        // 清空当前排班数据
                        scheduleData = [];

                        // 获取班次信息
                        var shiftId = json.bean.shiftId;
                        var startTime = json.bean.startTime;
                        var endTime = json.bean.endTime;

                        // 计算日期范围
                        var startDate = new Date(startTime.split(' ')[0]);
                        var endDate = new Date(endTime.split(' ')[0]);
                        var days = Math.floor((endDate - startDate) / (24 * 60 * 60 * 1000)) + 1;

                        // 处理每个时间段的数据
                        json.bean.schedulingTimeMation.forEach(function (timeSlot) {
                            // 处理每个工位的数据
                            if (timeSlot.schedulingTimeWorkMation && Array.isArray(timeSlot.schedulingTimeWorkMation)) {
                                timeSlot.schedulingTimeWorkMation.forEach(function (workstation) {
                                    // 处理每个员工的数据
                                    if (workstation.schedulingTimeWorkPeopleMation && Array.isArray(workstation.schedulingTimeWorkPeopleMation)) {
                                        workstation.schedulingTimeWorkPeopleMation.forEach(function (person) {
                                            // 查找员工详细信息
                                            var employee = employeeList.find(function (e) {
                                                return e.staffId === person.employeeId || e.id === person.employeeId;
                                            });

                                            // 为日期范围内的每一天创建排班记录
                                            for (var i = 0; i < days; i++) {
                                                var currentDate = new Date(startDate);
                                                currentDate.setDate(startDate.getDate() + i);
                                                var currentDateStr = formatDate(currentDate);
                                                var dayName = getDayOfWeek(currentDate);

                                                // 创建排班记录
                                                var scheduleItem = {
                                                    id: person.id + '-' + i,
                                                    date: currentDateStr,
                                                    scheduleDate: currentDateStr,
                                                    employeeId: person.employeeId,
                                                    employeeName: employee ? (employee.staffMation?.userName || employee.staffName || employee.name || '未知员工') : '未知员工',
                                                    jobNumber: employee ? (employee.staffMation?.jobNumber || employee.jobNumber || '') : '',
                                                    phone: employee ? (employee.staffMation?.phone || employee.phone || '') : '',
                                                    jobName: employee ? (employee.staffMation?.jobName || employee.jobName || '') : '',
                                                    shiftId: json.bean.shiftId,
                                                    shiftName: timeSlot.name || '',
                                                    shiftTimeId: timeSlot.id,
                                                    timeSlotId: getTimeSlotIdFromTime(timeSlot.startTime),
                                                    color: timeSlot.color || '#d44040',
                                                    startTime: timeSlot.startTime.substring(0, 5),
                                                    endTime: timeSlot.endTime.substring(0, 5),
                                                    workstationId: workstation.workId,
                                                    workshopId: json.bean.farmId,
                                                    scheduleType: json.bean.scheduleType || 1,
                                                    schedulePeopleType: 1,
                                                    schedulingTimeWorkId: workstation.id || '' // 保存排班时间工位id
                                                };

                                                // 添加到排班数据中
                                                scheduleData.push(scheduleItem);
                                            }
                                        });
                                    }
                                });
                            }
                        });

                        // 更新排班表
                        renderScheduleTable();

                        layer.msg('自动排班成功', { icon: 1 });
                    } else {
                        // 如果返回数据结构不完整，尝试重新获取排班数据
                        fetchScheduleData();
                        layer.msg('自动排班已完成，正在刷新数据', { icon: 1 });
                    }
                } else {
                    layer.msg(json.returnMessage || '自动排班失败', { icon: 2 });
                }
            },
            errorCallback: function (err) {
                layer.closeAll('loading');
                console.error('自动排班失败:', err);
                layer.msg('自动排班失败: ' + (err.returnMessage || err.msg || '未知错误'), { icon: 2 });
            }
        });
    }

    // 保存排班数据
    function saveSchedule() {
        if (scheduleData.length === 0) {
            layer.msg('请先进行排班', { icon: 0 });
            return;
        }

        // 获取表格中显示的七天时间范围
        var firstDay = null;
        var lastDay = null;
        scheduleData.forEach(function (schedule) {
            var currentDate = schedule.date || schedule.scheduleDate;
            if (currentDate && (!firstDay || currentDate < firstDay)) {
                firstDay = currentDate;
            }
            if (currentDate && (!lastDay || currentDate > lastDay)) {
                lastDay = currentDate;
            }
        });

        if (!firstDay || !lastDay) {
            layer.msg('无法获取排班时间范围', { icon: 0 });
            return;
        }

        // 生成schedulingTimeMation数组
        var schedulingTimeMation = [];

        // 遍历selectedShiftTimeMation中的每个时间段
        selectedShiftTimeMation.forEach(function (timeSlot) {
            // 创建时间段对象
            var timeSlotData = {
                startTime: timeSlot.startTime + ':00',
                endTime: timeSlot.endTime + ':00',
                isNextDay: timeSlot.isNextDay || 0,
                color: timeSlot.color || '#d44040',
                minStaff: timeSlot.minStaff || 0,
                maxStaff: timeSlot.maxStaff || 0,
                name: timeSlot.name || '',
                schedulingId: isEdit ? scheduleId : '',
                schedulingTimeWorkMation: [] // 工位信息数组
            };

            // 处理工位信息
            if (timeSlot.shiftsTimeWorkMation && Array.isArray(timeSlot.shiftsTimeWorkMation)) {
                timeSlot.shiftsTimeWorkMation.forEach(function (workStation) {
                    // 创建工位对象
                    var workStationData = {
                        workId: workStation.workId,
                        minStaff: workStation.minStaff || 0,
                        maxStaff: workStation.maxStaff || 0,
                        id: workStation.id,
                        schedulingId: isEdit ? scheduleId : '',
                        schedulingTimeWorkPeopleMation: [] // 员工信息数组
                    };

                    // 获取该工位在所有日期的排班员工
                    var workStationEmployees = scheduleData.filter(function (schedule) {
                        return (schedule.workstationId === workStation.workId ||
                            schedule.farmStationId === workStation.workId);
                    });

                    // 对员工数据进行分组和去重
                    var uniqueEmployees = {};
                    workStationEmployees.forEach(function (schedule) {
                        var employeeId = schedule.employeeId || schedule.staffId;
                        if (!uniqueEmployees[employeeId]) {
                            uniqueEmployees[employeeId] = {
                                id: schedule.id || (isEdit ? (scheduleId + '-' + schedule.date) : ''),
                                employeeId: employeeId,
                                schedulingId: isEdit ? scheduleId : '',
                                schedulingTimeWorkId: workStation.id
                            };
                        }
                    });

                    // 将去重后的员工数据添加到工位对象中
                    workStationData.schedulingTimeWorkPeopleMation = Object.values(uniqueEmployees);

                    // 只有当有员工排班时才添加工位信息
                    if (workStationData.schedulingTimeWorkPeopleMation.length > 0) {
                        timeSlotData.schedulingTimeWorkMation.push(workStationData);
                    }
                });
            }

            // 只有当有工位信息时才添加时间段
            if (timeSlotData.schedulingTimeWorkMation.length > 0) {
                schedulingTimeMation.push(timeSlotData);
            }
        });

        // 准备提交的数据
        var submitData = {
            shiftId: shiftId,
            scheduleType: isEdit ? 2 : 1, // 编辑模式下设置为2
            farmId: workshopId,
            startTime: firstDay + " 00:00",
            endTime: lastDay + " 23:59",
            schedulingTimeMation: JSON.stringify(schedulingTimeMation)
        };

        // 如果是编辑模式，添加ID
        if (isEdit && scheduleId) {
            submitData.id = scheduleId;
        }

        // 确认保存
        layer.confirm('确定要保存排班数据吗？', { icon: 3, title: '提示' }, function (index) {
            layer.close(index);
            layer.load(2);

            AjaxPostUtil.request({
                url: sysMainMation.checkworkBasePath + 'writeManualScheduling',
                params: submitData,
                type: 'json',
                method: "POST",
                callback: function (json) {
                    layer.closeAll('loading');
                    if (json) {
                        if (json.returnCode === 0 || json.result === 'success') {
                            layer.msg(json.returnMessage || json.msg || '保存成功', { icon: 1 });
                            if (!isEdit) {
                                setTimeout(function () {
                                    winui.window.close('排班管理');
                                }, 1500);
                            }
                        } else {
                            layer.msg(json.returnMessage || json.msg || '保存失败', { icon: 2 });
                        }
                    } else {
                        layer.msg('保存失败：服务器返回数据格式错误', { icon: 2 });
                    }
                },
                errorCallback: function (err) {
                    layer.closeAll('loading');
                    console.error("保存排班数据错误:", err);
                    layer.msg(err.returnMessage || err.msg || '保存失败，请检查网络连接', { icon: 2 });
                }
            });
        });
    }

    // 获取当前周的开始日期
    function getWeekStart() {
        var now = new Date();
        var weekStart = new Date(now);
        weekStart.setDate(now.getDate() - now.getDay());
        return formatDate(weekStart);
    }

    // 获取当前周的结束日期
    function getWeekEnd() {
        var now = new Date();
        var weekEnd = new Date(now);
        weekEnd.setDate(now.getDate() + (6 - now.getDay()));
        return formatDate(weekEnd);
    }

    // 格式化日期为YYYY-MM-DD
    function formatDate(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        return year + '-' + month + '-' + day;
    }

    // 获取URL参数
    function getUrlParams() {
        var params = {};
        var query = window.location.search.substring(1);
        var vars = query.split('&');
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split('=');
            params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
        }
        return params;
    }

    // 生成从00:00到24:00的时间段，每30分钟一个
    function generateTimeSlots() {
        var slots = [];
        var totalSlots = 24 * 60 / 30; // 每30分钟一个时间段，共48个时间段

        for (var i = 0; i < totalSlots; i++) {
            // 计算开始时间
            var totalMinutesStart = i * 30;
            var hoursStart = Math.floor(totalMinutesStart / 60);
            var minutesStart = totalMinutesStart % 60;

            // 计算结束时间
            var totalMinutesEnd = (i + 1) * 30;
            var hoursEnd = Math.floor(totalMinutesEnd / 60);
            var minutesEnd = totalMinutesEnd % 60;

            // 格式化时间字符串
            var startTime = hoursStart.toString().padStart(2, '0') + ':' + minutesStart.toString().padStart(2, '0');
            var endTime = hoursEnd.toString().padStart(2, '0') + ':' + minutesEnd.toString().padStart(2, '0');


            slots.push({
                id: String(i + 1),
                name: startTime + '-' + endTime,
                startTime: startTime,
                endTime: endTime
            });
        }

        return slots;
    }

    // 获取车间列表数据
    function fetchWorkshopList(callback) {
        AjaxPostUtil.request({
            url: sysMainMation.erpBasePath + 'queryStaffBelongFarmList',
            params: {},
            type: 'json',
            method: "GET",
            callback: function (json) {
                if (json.returnCode === 0) {
                    var workshops = json.rows || [];
                    // 更新车间下拉框
                    var options = '<option value="">请选择车间</option>';
                    workshops.forEach(function (workshop) {
                        options += '<option value="' + workshop.id + '">' + workshop.name + '</option>';
                    });
                    $('#workshopSelect').html(options);
                    form.render('select');

                    if (callback) callback(true, null, workshops);
                } else {
                    console.error('获取车间列表失败:', json.msg);
                    if (callback) callback(false, json.msg || '获取车间数据失败');
                }
            },
            errorCallback: function (err) {
                console.error("获取车间列表错误:", err);
                if (callback) callback(false, '获取车间数据失败，请检查网络连接');
            }
        });
    }

    // 初始化车间下拉框
    function fetchWorkShop() {
        fetchWorkshopList(function (success, error, workshops) {
            layer.closeAll('loading');

            if (success) {
                // 如果URL中有车间ID，则选中对应车间
                if (workshopId) {
                    $('#workshopSelect').val(workshopId);
                    form.render('select');
                    handleWorkshopChange(workshopId);
                } else if (workshops.length > 0) {
                    // 否则自动选中第一个车间
                    $('#workshopSelect').val(workshops[0].id);
                    form.render('select');
                    handleWorkshopChange(workshops[0].id);
                }

                // 获取班次数据
                fetchShifts();
            } else {
                layer.msg(error || '获取车间数据失败', { icon: 2 });
            }
        });
    }

    // 处理车间变化
    function handleWorkshopChange(value) {
        workshopId = value;
        // 清空当前员工数据
        employeeList = [];
        filteredEmployees = [];

        // 关闭所有loading
        layer.closeAll('loading');
        layer.load(2);

        // 获取员工数据
        fetchEmployeeList(function (success, error) {
            if (success) {
                // 获取工位数据
                fetchWorkstationList(function (success, error, stations) {
                    if (success) {
                        // 获取班次数据
                        fetchShiftsList(function (success, error, shifts) {
                            if (success) {

                                // 如果有预设的班次ID，则选中它
                                if (shiftId) {
                                    $('#shiftSelect').val(shiftId);
                                    form.render('select');
                                    handleShiftChange(shiftId);
                                } else if (shifts.length > 0) {
                                    $('#shiftSelect').val(shifts[0].id);
                                    form.render('select');
                                    handleShiftChange(shifts[0].id);
                                }

                                // 获取排班数据
                                fetchScheduleData();
                                layer.closeAll('loading');
                            } else {
                                layer.msg(error || '获取班次数据失败', { icon: 2 });
                                layer.closeAll('loading');
                            }
                        });
                    } else {
                        layer.msg(error || '获取工位数据失败', { icon: 2 });
                        layer.closeAll('loading');
                    }
                });
            } else {
                layer.msg(error || '获取员工数据失败', { icon: 2 });
                layer.closeAll('loading');
            }
        });
    }

    // 获取班次列表数据
    function fetchShiftsList(callback) {
        if (!workshopId) {
            console.warn('获取班次列表时workshopId为空');
            if (callback) callback(false, '车间ID不能为空');
            return;
        }

        AjaxPostUtil.request({
            url: sysMainMation.checkworkBasePath + 'querySchedulingShiftsList',
            params: {
                holderId: workshopId,
                page: 1,
                limit: 10000
            },
            type: 'json',
            method: "POST",
            callback: function (json) {
                if (json.returnCode === 0) {
                    shiftList = json.rows || [];
                    // 更新班次下拉框
                    var options = '<option value="">请选择班次</option>';
                    shiftList.forEach(function (shift) {
                        options += '<option value="' + shift.id + '">' + shift.name + '</option>';
                    });
                    $('#shiftSelect').html(options);
                    form.render('select');

                    if (callback) callback(true, null, shiftList);
                } else {
                    console.error('获取班次列表失败:', json.returnMessage);
                    if (callback) callback(false, json.returnMessage || '获取班次数据失败');
                }
            },
            errorCallback: function (err) {
                console.error("获取班次列表错误:", err);
                if (callback) callback(false, '获取班次数据失败，请检查网络连接');
            }
        });
    }

    // 获取班次数据
    function fetchShifts() {
        fetchShiftsList(function (success, error) {
            layer.closeAll('loading');

            if (success) {
                // 如果是编辑模式，获取排班详情
                if (isEdit && scheduleId) {
                    fetchScheduleDetail();
                } else if (shiftList.length > 0) {
                    // 否则自动选中第一个班次
                    $('#shiftSelect').val(shiftList[0].id);
                    form.render('select');
                    handleShiftChange(shiftList[0].id);
                }

                // 获取排班数据
                fetchScheduleData();
            } else {
                layer.msg(error || '获取班次数据失败', { icon: 2 });
            }
        });
    }

    // 获取工位数据
    var workstationList = [];
    // 获取员工列表数据
    function fetchEmployeeList(callback) {
        if (!workshopId) {
            console.warn('获取员工列表时workshopId为空');
            if (callback) callback(false, '车间ID不能为空');
            return;
        }

        AjaxPostUtil.request({
            url: sysMainMation.erpBasePath + 'queryFarmStaffList',
            params: {
                objectId: workshopId,
                limit: 10000,
                page: 1
            },
            type: 'json',
            method: "POST",
            callback: function (json) {
                if (json.returnCode === 0) {
                    employeeList = json.rows || [];
                    filteredEmployees = [...employeeList];
                    renderEmployeeList();
                    if (callback) callback(true, null, employeeList);
                } else {
                    console.error('获取员工列表失败:', json.msg);
                    if (callback) callback(false, json.msg || '获取员工数据失败');
                }
            },
            errorCallback: function (err) {
                console.error("获取员工列表错误:", err);
                if (callback) callback(false, '获取员工数据失败，请检查网络连接');
            }
        });
    }

    // 渲染员工列表
    function renderEmployeeList() {
        var html = '';
        if (filteredEmployees.length === 0) {
            html = '<div class="no-data">暂无员工数据</div>';
        } else {
            filteredEmployees.forEach(function (employee) {
                var staffMation = employee.staffMation || {};
                var userName = staffMation.userName || employee.staffName || employee.name || '未知员工';
                var jobNumber = staffMation.jobNumber || employee.jobNumber || '';
                var phone = staffMation.phone || employee.phone || '';
                var jobName = staffMation.jobName || employee.jobName || '';

                html += '<div class="employee-item" draggable="true" data-employee=\'' + JSON.stringify(employee) + '\'>';
                html += '<div class="employee-card">';
                html += '<div class="employee-name">' + userName + '</div>';
                html += '<div class="employee-info">';
                html += '<div class="employee-job-number">工号: ' + jobNumber + '</div>';
                html += '<div class="employee-phone">电话: ' + phone + '</div>';
                if (jobName) {
                    html += '<div class="employee-position">职位: ' + jobName + '</div>';
                }
                html += '</div></div></div>';
            });
        }
        $('#employeeList').html(html);

        // 添加拖拽事件
        setupDragEvents();
    }

    // 设置拖拽事件
    function setupDragEvents() {
        // 拖拽开始
        $('.employee-item').on('dragstart', function (e) {
            e.originalEvent.dataTransfer.setData('text/plain', $(this).attr('data-employee'));
            $(this).addClass('dragging');
        });

        // 拖拽结束
        $('.employee-item').on('dragend', function () {
            $(this).removeClass('dragging');
        });

        // 工位区域拖放事件
        $('.work-station-info').on('dragover', function (e) {
            e.preventDefault();
            $(this).addClass('dragover');
        });

        $('.work-station-info').on('dragleave', function () {
            $(this).removeClass('dragover');
        });

        $('.work-station-info').on('drop', function (e) {
            e.preventDefault();
            $(this).removeClass('dragover');

            try {
                var employeeData = JSON.parse(e.originalEvent.dataTransfer.getData('text/plain'));
                var workstationId = $(this).data('work-id');
                var $cell = $(this).closest('td');
                var dayIndex = $cell.data('day-index');
                var timeSlotId = $cell.data('time-slot-id');
                var date = $cell.data('date');

                if (date && timeSlotId && workstationId) {
                    // 创建一个表示当天的对象
                    var day = {
                        fullDate: date,
                        dayOfWeek: dayIndex
                    };

                    // 调用添加员工到排班表的函数
                    addEmployeeToSchedule(employeeData, day, timeSlotId, workstationId);
                }
            } catch (error) {
                console.error("拖放处理错误:", error);
            }
        });

        // 班次单元格拖放事件（用于没有工位信息的情况）
        $('.shift-active-cell').on('dragover', function (e) {
            e.preventDefault();
            $(this).addClass('dragover');
        });

        $('.shift-active-cell').on('dragleave', function () {
            $(this).removeClass('dragover');
        });

        $('.shift-active-cell').on('drop', function (e) {
            e.preventDefault();
            $(this).removeClass('dragover');

            try {
                var employeeData = JSON.parse(e.originalEvent.dataTransfer.getData('text/plain'));
                var dayIndex = $(this).data('day-index');
                var timeSlotId = $(this).data('time-slot-id');
                var date = $(this).data('date');

                if (date && timeSlotId) {
                    // 创建一个表示当天的对象
                    var day = {
                        fullDate: date,
                        dayOfWeek: dayIndex
                    };

                    // 查找该单元格对应的班次信息
                    var shiftTimeInfo = null;
                    if (selectedShiftTimeMation && selectedShiftTimeMation.length > 0) {
                        for (var i = 0; i < selectedShiftTimeMation.length; i++) {
                            var slot = selectedShiftTimeMation[i];
                            var startSlotId = parseInt(getTimeSlotIdFromTime(slot.startTime));
                            var endSlotId = parseInt(getTimeSlotIdFromTime(slot.endTime));
                            var currentSlotId = parseInt(timeSlot.id);

                            // 检查是否是跨天时间段
                            var isOvernight = endSlotId <= startSlotId;

                            if (isOvernight) {
                                // 第一部分：从开始时间到24:00
                                if (currentSlotId >= startSlotId && currentSlotId <= 48) {
                                    shiftTimeInfo = slot;
                                    break;
                                }
                                // 第二部分：从00:00到结束时间
                                // 注意：这里修改了判断条件，确保不会超过结束时间
                                if (currentSlotId >= 1 && currentSlotId <= endSlotId) {
                                    shiftTimeInfo = slot;
                                    isNextDayPart = true;
                                    break;
                                }
                            } else {
                                // 普通时间段
                                if (currentSlotId >= startSlotId && currentSlotId < endSlotId) {
                                    shiftTimeInfo = slot;
                                    break;
                                }
                            }
                        }
                    }

                    if (shiftTimeInfo && shiftTimeInfo.shiftsTimeWorkMation && shiftTimeInfo.shiftsTimeWorkMation.length > 0) {
                        // 如果有工位信息，使用第一个工位
                        var workstationId = shiftTimeInfo.shiftsTimeWorkMation[0].workId || shiftTimeInfo.shiftsTimeWorkMation[0].id;
                        addEmployeeToSchedule(employeeData, day, timeSlotId, workstationId);
                    } else {
                        // 如果没有工位信息，使用默认工位
                        addEmployeeToSchedule(employeeData, day, timeSlotId, 'default');
                    }
                }
            } catch (error) {
                console.error("拖放处理错误:", error);
            }
        });
    }

    // 添加员工到排班表
    function addEmployeeToSchedule(employee, day, timeSlotId, workstationId) {

        // 如果没有工位ID，使用默认值
        workstationId = workstationId || 'default';

        // 检查是否在选中的班次时间段内
        var shiftTimeInfo = null;
        if (selectedShiftTimeMation && selectedShiftTimeMation.length > 0) {

            // 先检查是否精确匹配当前时间段
            shiftTimeInfo = selectedShiftTimeMation.find(function (slot) {
                return getTimeSlotIdFromTime(slot.startTime) === timeSlotId;
            });

            // 如果没有精确匹配，检查是否在某个班次时间段的范围内
            if (!shiftTimeInfo) {
                for (var i = 0; i < selectedShiftTimeMation.length; i++) {
                    var slot = selectedShiftTimeMation[i];
                    var startSlotId = parseInt(getTimeSlotIdFromTime(slot.startTime));
                    var endSlotId = parseInt(getTimeSlotIdFromTime(slot.endTime));
                    var currentSlotId = parseInt(timeSlotId);

                    // 特殊处理00:00的情况
                    if (slot.endTime === '00:00' || slot.endTime.endsWith('00:00:00')) {
                        endSlotId = 48; // 一天的最后一个时间段
                    }

                    // 如果结束ID小于开始ID，说明跨天了，这里简化处理，只考虑当天
                    if (endSlotId <= startSlotId) {
                        endSlotId = 48; // 设置为一天的最后一个时间段
                    }

                    if (currentSlotId >= startSlotId && currentSlotId < endSlotId) {
                        shiftTimeInfo = slot;
                        break;
                    }
                }
            }
        }

        // 如果不在班次时间段内，不允许排班
        if (!shiftTimeInfo) {
            layer.msg('只能在班次定义的时间段内排班', { icon: 2 });
            console.error('未找到匹配的班次时间段');
            return;
        }

        // 从全天时间段中获取基本信息
        var allTimeSlots = generateTimeSlots();
        var timeSlot = allTimeSlots.find(function (slot) {
            return slot.id === timeSlotId;
        });

        if (!timeSlot) {

            // 创建一个默认的时间段对象，避免后续代码出错
            var slotIndex = parseInt(timeSlotId) - 1;
            if (slotIndex >= 0 && slotIndex < 48) {
                var hours = Math.floor(slotIndex / 2);
                var minutes = (slotIndex % 2) * 30;
                var hoursEnd = Math.floor((slotIndex + 1) / 2);
                var minutesEnd = ((slotIndex + 1) % 2) * 30;

                var startTime = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0');
                var endTime = hoursEnd.toString().padStart(2, '0') + ':' + minutesEnd.toString().padStart(2, '0');

                timeSlot = {
                    id: timeSlotId,
                    name: startTime + '-' + endTime,
                    startTime: startTime,
                    endTime: endTime
                };

            } else {
                layer.msg('无法找到对应的时间段信息', { icon: 2 });
                return;
            }
        }

        // 查找工位信息
        var workstationInfo = null;

        // 从班次时间段的工位信息中查找
        if (shiftTimeInfo.shiftsTimeWorkMation && shiftTimeInfo.shiftsTimeWorkMation.length > 0) {
            workstationInfo = shiftTimeInfo.shiftsTimeWorkMation.find(function (ws) {
                return ws.workId === workstationId || ws.id === workstationId;
            });
        }

        // 如果在班次时间段中没找到，从工位列表中查找
        if (!workstationInfo) {
            workstationInfo = workstationList.find(function (ws) {
                return ws.id === workstationId;
            }) || {};
        }

        // 获取整周的日期
        var weekDaysToSchedule = [...weekDays]; // 复制整周日期数组

        // 记录成功排班的日期
        var successfulDays = [];
        var failedDays = [];

        // 为整周的每一天进行排班
        weekDaysToSchedule.forEach(function (currentDay) {

            // 检查工位人数是否已满
            var startSlotId = parseInt(getTimeSlotIdFromTime(shiftTimeInfo.startTime));
            var endSlotId = parseInt(getTimeSlotIdFromTime(shiftTimeInfo.endTime));

            // 如果结束时间是00:00，表示是第二天的凌晨，对应的是时间段48
            if (shiftTimeInfo.endTime === '00:00' || shiftTimeInfo.endTime.endsWith('00:00:00')) {
                endSlotId = 48;
            }

            // 如果结束ID小于开始ID，说明跨天了，这里简化处理，只考虑当天
            if (endSlotId <= startSlotId) {
                endSlotId = 48; // 设置为一天的最后一个时间段
            }

            // 检查该员工在当前日期和时间段是否已经排班
            var isAlreadyScheduled = scheduleData.some(function (schedule) {
                var employeeMatch = (schedule.employeeId === (employee.staffId || employee.id));
                var dateMatch = (schedule.date === currentDay.fullDate || schedule.scheduleDate === currentDay.fullDate);
                var timeMatch = (parseInt(schedule.timeSlotId) === parseInt(timeSlotId));

                return employeeMatch && dateMatch && timeMatch;
            });

            if (isAlreadyScheduled) {
                failedDays.push(currentDay.name + '(' + currentDay.date + ')');
                return; // 跳过这一天
            }

            // 检查当前日期和时间段的工位人数是否已满
            var scheduledEmployees = [];
            for (var i = startSlotId; i < endSlotId; i++) {
                var slotEmployees = scheduleData.filter(function (schedule) {
                    // 检查日期匹配 - 支持date和scheduleDate两个字段
                    var dateMatch = (schedule.date === currentDay.fullDate || schedule.scheduleDate === currentDay.fullDate);

                    // 检查时间段匹配 - 支持timeSlotId字符串或数字
                    var timeMatch = (schedule.timeSlotId === String(i) || schedule.timeSlotId === i);

                    // 检查工位匹配 - 支持多种字段名
                    var workstationMatch = false;
                    if (workstationId) {
                        workstationMatch =
                            (schedule.workstationId && schedule.workstationId.toString() === workstationId.toString()) ||
                            (schedule.farmStationId && schedule.farmStationId.toString() === workstationId.toString()) ||
                            (schedule.workId && schedule.workId.toString() === workstationId.toString());
                    }

                    return dateMatch && timeMatch && workstationMatch;
                });

                scheduledEmployees = scheduledEmployees.concat(slotEmployees);
            }

            var maxStaff = workstationInfo.maxStaff || shiftTimeInfo.maxStaff || 0;

            if (maxStaff > 0 && scheduledEmployees.length >= maxStaff) {
                failedDays.push(currentDay.name + '(' + currentDay.date + ')');
                return; // 跳过这一天
            }

            // 创建排班记录
            var scheduleItem = {
                id: isEdit ? (scheduleId + '-' + currentDay.fullDate) : (new Date().getTime() + '-' + Math.floor(Math.random() * 1000) + '-' + currentDay.fullDate),
                date: currentDay.fullDate,
                scheduleDate: currentDay.fullDate,
                employeeId: employee.staffId || employee.id,
                employeeName: employee.staffMation?.userName || employee.staffName || employee.name,
                jobNumber: employee.staffMation?.jobNumber || employee.jobNumber || '',
                phone: employee.staffMation?.phone || employee.phone || '',
                jobName: employee.staffMation?.jobName || employee.jobName || '',
                shiftId: $('#shiftSelect').val(),
                shiftName: shiftTimeInfo.name || '',
                shiftTimeId: shiftTimeInfo.id,
                timeSlotId: timeSlotId,
                color: shiftTimeInfo.color || '#1890ff',
                startTime: timeSlot.startTime,
                endTime: timeSlot.endTime,
                workstationId: workstationId,
                workstationName: workstationInfo.name || workstationInfo.workName || '工位' + workstationId,
                workshopId: workshopId,
                scheduleType: 1,
                schedulePeopleType: 1
            };

            // 添加到排班数据
            scheduleData.push(scheduleItem);
            successfulDays.push(currentDay.name + '(' + currentDay.date + ')');
        });

        // 渲染排班表
        renderScheduleTable();

        // 确保更新已排班员工数量
        updateScheduledEmployeesCount();

        // 显示排班结果
        if (successfulDays.length > 0) {
            if (failedDays.length > 0) {
                layer.msg('部分排班成功，' + failedDays.join('、') + ' 排班失败（可能已排班或人数已满）', { icon: 1 });
            } else {
                layer.msg('整周排班成功', { icon: 1 });
            }
        } else if (failedDays.length < 0) {
            layer.msg('排班失败，所选时间段可能已排满或已有排班', { icon: 2 });
        }
    }

    // 获取排班数据
    function fetchScheduleData() {
        if (!workshopId) {
            return;
        }

        var startDate = $('#startDate').val();
        var endDate = $('#endDate').val();

        if (!startDate || !endDate) {
            startDate = getWeekStart();
            endDate = getWeekEnd();
            $('#startDate').val(startDate);
            $('#endDate').val(endDate);
        }

        AjaxPostUtil.request({
            url: sysMainMation.checkworkBasePath + 'querySchedulingList',
            params: {
                holderId: workshopId,
                startDate: startDate,
                endDate: endDate,
                limit: 10000,
                page: 1
            },
            type: 'json',
            method: "POST",
            callback: function (json) {
                if (json.returnCode === 0) {
                    // 确保scheduleData是数组
                    scheduleData = Array.isArray(json.rows) ? json.rows : [];

                    // 处理每条排班记录，确保必要的字段存在
                    scheduleData = scheduleData.map(function (item) {
                        return {
                            ...item,
                            date: item.date || item.scheduleDate,
                            employeeId: item.employeeId || item.staffId,
                            workstationId: item.workstationId || item.farmStationId
                        };
                    });

                    // 更新周日期
                    updateWeekDays(startDate, endDate);

                    // 渲染排班表
                    renderScheduleTable();
                } else {
                    console.error('获取排班数据失败:', json.returnMessage);
                    layer.msg(json.returnMessage || '获取排班数据失败', { icon: 2 });
                }
            },
            errorCallback: function (err) {
                console.error('获取排班数据失败:', err);
                layer.msg('获取排班数据失败，请检查网络连接', { icon: 2 });
            }
        });
    }

    // 更新周日期
    function updateWeekDays(startDate, endDate) {
        weekDays = [];
        var dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

        var start = new Date(startDate);
        var end = new Date(endDate);
        var days = Math.floor((end - start) / (24 * 60 * 60 * 1000)) + 1;

        for (var i = 0; i < days; i++) {
            var currentDay = new Date(start);
            currentDay.setDate(start.getDate() + i);

            weekDays.push({
                date: formatDate(currentDay).substring(5), // MM-DD
                name: dayNames[currentDay.getDay()],
                fullDate: formatDate(currentDay),
                dayOfWeek: currentDay.getDay(),
                selected: false
            });
        }
    }

    // 获取排班记录详情
    function fetchScheduleDetail() {
        if (!scheduleId) return;

        layer.load(2);

        AjaxPostUtil.request({
            url: sysMainMation.checkworkBasePath + 'querySchedulingById',
            params: { id: scheduleId },
            type: 'json',
            method: "POST",
            callback: function (json) {
                layer.closeAll('loading');

                if (json.bean) {
                    // 设置车间
                    workshopId = json.bean.farmId;

                    // 保存班次ID以供后续使用
                    shiftId = json.bean.shiftId;

                    // 设置日期范围
                    if (json.bean.startTime && json.bean.endTime) {
                        var startTime = json.bean.startTime.split(' ')[0];
                        var endTime = json.bean.endTime.split(' ')[0];
                        $('#startDate').val(startTime);
                        $('#endDate').val(endTime);
                        startDate = startTime;
                        endDate = endTime;
                    }

                    // 获取员工数据
                    fetchEmployeeList(function (success, error) {
                        if (success) {
                            // 获取车间列表并设置选中值
                            fetchWorkshopList(function (success, error) {
                                if (success) {
                                    // 设置选中的车间
                                    $('#workshopSelect').val(workshopId);
                                    form.render('select');

                                    // 获取工位数据
                                    fetchWorkstationList(function (success, error) {
                                        if (success) {
                                            // 获取班次数据
                                            fetchShiftsList(function (success, error) {
                                                if (success) {
                                                    // 设置选中的班次
                                                    $('#shiftSelect').val(shiftId);
                                                    form.render('select');

                                                    // 处理排班数据
                                                    if (json.bean.schedulingTimeMation) {
                                                        var schedulingData = [];
                                                        try {
                                                            // 尝试解析schedulingTimeMation
                                                            var timeMations = typeof json.bean.schedulingTimeMation === 'string' ?
                                                                JSON.parse(json.bean.schedulingTimeMation) : json.bean.schedulingTimeMation;

                                                            // 处理每个时间段的数据
                                                            timeMations.forEach(function (timeSlot) {
                                                                if (timeSlot.schedulingTimeWorkMation) {
                                                                    timeSlot.schedulingTimeWorkMation.forEach(function (workstation) {
                                                                        if (workstation.schedulingTimeWorkPeopleMation) {
                                                                            workstation.schedulingTimeWorkPeopleMation.forEach(function (person) {
                                                                                // 查找员工详细信息
                                                                                var employee = employeeList.find(function (e) {
                                                                                    return e.staffId === person.employeeId || e.id === person.employeeId;
                                                                                });

                                                                                if (employee) {
                                                                                    // 计算日期范围内的每一天
                                                                                    var start = new Date(startTime);
                                                                                    var end = new Date(endTime);
                                                                                    var days = Math.floor((end - start) / (24 * 60 * 60 * 1000)) + 1;

                                                                                    // 为每一天创建排班记录
                                                                                    for (var i = 0; i < days; i++) {
                                                                                        var currentDate = new Date(start);
                                                                                        currentDate.setDate(start.getDate() + i);
                                                                                        var currentDateStr = formatDate(currentDate);

                                                                                        // 检查是否已经存在该员工在当天的排班记录
                                                                                        var existingRecord = schedulingData.find(function (record) {
                                                                                            return record.employeeId === person.employeeId &&
                                                                                                record.date === currentDateStr &&
                                                                                                record.timeSlotId === getTimeSlotIdFromTime(timeSlot.startTime) &&
                                                                                                record.workstationId === workstation.workId;
                                                                                        });

                                                                                        // 如果不存在，才添加新记录
                                                                                        if (!existingRecord) {
                                                                                            var scheduleItem = {
                                                                                                id: person.id + '-' + currentDateStr,
                                                                                                date: currentDateStr,
                                                                                                scheduleDate: currentDateStr,
                                                                                                employeeId: person.employeeId,
                                                                                                employeeName: employee.staffMation?.userName || employee.staffName || employee.name || '未知员工',
                                                                                                jobNumber: employee.staffMation?.jobNumber || employee.jobNumber || '',
                                                                                                phone: employee.staffMation?.phone || employee.phone || '',
                                                                                                jobName: employee.staffMation?.jobName || employee.jobName || '',
                                                                                                shiftId: shiftId,
                                                                                                shiftTimeId: timeSlot.id,
                                                                                                timeSlotId: getTimeSlotIdFromTime(timeSlot.startTime),
                                                                                                color: timeSlot.color || '#1890ff',
                                                                                                startTime: timeSlot.startTime,
                                                                                                endTime: timeSlot.endTime,
                                                                                                workstationId: workstation.workId,
                                                                                                workshopId: workshopId,
                                                                                                scheduleType: 1,
                                                                                                schedulePeopleType: 1
                                                                                            };
                                                                                            schedulingData.push(scheduleItem);
                                                                                        }
                                                                                    }
                                                                                }
                                                                            });
                                                                        }
                                                                    });
                                                                }
                                                            });

                                                            // 更新scheduleData
                                                            scheduleData = schedulingData;

                                                            // 更新周日期
                                                            updateWeekDays(startTime, endTime);

                                                            // 获取班次时间段信息并重新渲染表格
                                                            handleShiftChange(shiftId);
                                                        } catch (e) {
                                                            console.error('解析排班数据失败:', e);
                                                            layer.msg('解析排班数据失败', { icon: 2 });
                                                        }
                                                    }
                                                } else {
                                                    layer.msg(error || '获取班次数据失败', { icon: 2 });
                                                }
                                            });
                                        } else {
                                            layer.msg(error || '获取工位数据失败', { icon: 2 });
                                        }
                                    });
                                } else {
                                    layer.msg(error || '获取车间数据失败', { icon: 2 });
                                }
                            });
                        } else {
                            layer.msg(error || '获取员工数据失败', { icon: 2 });
                        }
                    });
                } else {
                    layer.msg('获取排班详情失败', { icon: 2 });
                }
            },
            errorCallback: function (err) {
                layer.closeAll('loading');
                console.error('获取排班详情失败:', err);
                layer.msg('获取排班详情失败，请检查网络连接', { icon: 2 });
            }
        });
    }

    // 根据时间获取时间段ID
    function getTimeSlotIdFromTime(time) {
        if (!time) return null;

        // 处理不同的时间格式
        var timeStr = time;
        if (time.indexOf(' ') > -1) {
            timeStr = time.split(' ')[1];
        }

        // 移除秒数部分
        timeStr = timeStr.split(':').slice(0, 2).join(':');

        var parts = timeStr.split(':');
        var hours = parseInt(parts[0]);
        var minutes = parseInt(parts[1]);

        if (isNaN(hours) || isNaN(minutes)) {
            console.error('无效的时间格式:', time);
            return null;
        }

        // 计算时间段索引（每30分钟一个时间段）
        var totalMinutes = hours * 60 + minutes;
        var slotIndex = Math.floor(totalMinutes / 30);

        // 时间段ID是1-48，索引是0-47
        return String(slotIndex + 1);
    }

    // 获取班次详情
    function fetchShiftDetail(shiftId) {

        // 显示加载层
        layer.load(2);

        // 返回Promise以便异步处理
        return new Promise(function (resolve, reject) {
            // 先尝试从本地班次列表中获取
            var shift = shiftList.find(function (s) { return s.id === shiftId; });
            if (shift && shift.schedulingShiftsTimeMation) {
                try {
                    var timeSlots = [];

                    if (typeof shift.schedulingShiftsTimeMation === 'string') {
                        timeSlots = JSON.parse(shift.schedulingShiftsTimeMation);
                    } else if (Array.isArray(shift.schedulingShiftsTimeMation)) {
                        timeSlots = shift.schedulingShiftsTimeMation;
                    } else {
                        timeSlots = [];
                    }

                    // 确保时间段有正确的格式
                    timeSlots = formatTimeSlots(timeSlots);

                    // 返回处理后的时间段
                    resolve(timeSlots);
                    return;
                } catch (e) {
                    console.error('解析班次时间段失败:', e);
                    // 如果解析失败，继续尝试通过API获取
                }
            }

            // 如果本地获取失败，则通过API获取
            AjaxPostUtil.request({
                url: sysMainMation.checkworkBasePath + 'querySchedulingShiftsById',
                params: { id: shiftId },
                type: 'json',
                method: "POST",
                callback: function (json) {

                    if (json.returnCode === 0 && json.bean) {
                        // 处理时间段信息
                        var timeSlots = [];

                        // 直接从bean中获取schedulingShiftsTimeMation
                        if (json.bean.schedulingShiftsTimeMation) {
                            if (typeof json.bean.schedulingShiftsTimeMation === 'string') {
                                try {
                                    timeSlots = JSON.parse(json.bean.schedulingShiftsTimeMation);
                                } catch (e) {
                                    console.error('解析班次时间段数据失败:', e);
                                    timeSlots = [];
                                }
                            } else if (Array.isArray(json.bean.schedulingShiftsTimeMation)) {
                                timeSlots = json.bean.schedulingShiftsTimeMation;
                            }
                        }
                        // 如果bean中没有，则尝试从原始班次列表中获取
                        else {
                            // 查找当前班次
                            var currentShift = shiftList.find(function (shift) {
                                return shift.id === shiftId;
                            });

                            if (currentShift && currentShift.schedulingShiftsTimeMation) {
                                if (typeof currentShift.schedulingShiftsTimeMation === 'string') {
                                    try {
                                        timeSlots = JSON.parse(currentShift.schedulingShiftsTimeMation);
                                    } catch (e) {
                                        console.error('解析班次时间段数据失败:', e);
                                        timeSlots = [];
                                    }
                                } else if (Array.isArray(currentShift.schedulingShiftsTimeMation)) {
                                    timeSlots = currentShift.schedulingShiftsTimeMation;
                                }
                            }
                        }

                        // 确保时间段有正确的格式
                        timeSlots = formatTimeSlots(timeSlots);

                        resolve(timeSlots);
                    } else {
                        console.error('获取班次详情失败:', json.returnMessage || '未知错误');
                        reject(json.returnMessage || '获取班次详情失败');
                    }
                },
                errorCallback: function (err) {
                    console.error("获取班次详情错误:", err);
                    reject('获取班次详情失败，请检查网络连接');
                }
            });
        });
    }

    // 格式化时间段数据，确保id和时间格式正确
    function formatTimeSlots(timeSlots) {
        return timeSlots.map(function (slot, index) {
            // 如果没有id，使用索引+1作为id
            if (!slot.id) {
                slot.id = String(index + 1);
            }

            // 确保startTime和endTime是字符串格式
            if (slot.startTime && typeof slot.startTime !== 'string') {
                slot.startTime = String(slot.startTime);
            }
            if (slot.endTime && typeof slot.endTime !== 'string') {
                slot.endTime = String(slot.endTime);
            }

            // 确保color属性存在
            if (!slot.color) {
                slot.color = '#e74c3c'; // 默认红色
            }

            // 处理工位信息
            if (slot.shiftsTimeWorkMation) {
                // 如果是字符串，尝试解析为JSON
                if (typeof slot.shiftsTimeWorkMation === 'string') {
                    try {
                        slot.shiftsTimeWorkMation = JSON.parse(slot.shiftsTimeWorkMation);
                    } catch (e) {
                        console.error('解析工位信息失败:', e);
                        slot.shiftsTimeWorkMation = [];
                    }
                }
                // 如果不是数组，设置为空数组
                else if (!Array.isArray(slot.shiftsTimeWorkMation)) {
                    slot.shiftsTimeWorkMation = [];
                }
            } else {
                slot.shiftsTimeWorkMation = [];
            }

            return slot;
        });
    }

    // 处理班次变化
    function handleShiftChange(value) {
        if (!value) {
            selectedShiftTimeMation = [];
            shiftId = ''; // 清空shiftId
            displayShiftTimesInfo();
            renderScheduleTable();
            return;
        }

        shiftId = value; // 设置shiftId
        layer.load(2);

        // 调用获取班次详情的函数
        fetchShiftDetail(value)
            .then(function (timeSlots) {
                selectedShiftTimeMation = timeSlots;
                // 关闭加载层
                layer.closeAll('loading');

                // 显示班次时间段信息
                displayShiftTimesInfo();

                // 重新渲染排班表
                renderScheduleTable();
            })
            .catch(function (error) {
                console.error('获取班次详情失败:', error);

                // 关闭加载层
                layer.closeAll('loading');

                // 显示错误信息
                layer.msg(error || '获取班次详情失败', { icon: 2 });

                // 清空时间段
                selectedShiftTimeMation = [];

                // 更新界面
                displayShiftTimesInfo();
                renderScheduleTable();
            });
    }

    // 渲染排班表格
    function renderScheduleTable() {
        if (!startDate || !endDate) {
            $('#scheduleTable').html('<div class="no-data">请先选择日期范围</div>');
            return;
        }

        // 计算日期范围
        var dateRange = getDateRange(startDate, endDate);

        // 创建表头
        var $thead = $('<thead></thead>');
        var $headerRow = $('<tr></tr>');
        $headerRow.append('<th class="time-column">时间段</th>');

        // 添加日期列
        dateRange.forEach(function (day) {
            var dayName = getDayOfWeek(day);
            var dateStr = formatDate(day, 'MM-DD');
            var $dayHeader = $('<th class="day-column" data-date="' + formatDate(day, 'YYYY-MM-DD') + '"></th>');
            var dayHeaderContent = '<div class="day-header">' +
                '<div class="week-day">' + dayName + '</div>' +
                '<div class="day-date">' + dateStr + '</div>' +
                '</div>';
            $dayHeader.html(dayHeaderContent);
            $headerRow.append($dayHeader);
        });

        $thead.append($headerRow);

        // 创建表格主体
        var $tbody = $('<tbody></tbody>');

        // 生成时间段
        var timeSlots = generateTimeSlots();

        // 创建一个对象来跟踪每个日期和班次的合并单元格
        var mergedCells = {};

        // 为每个时间段创建行
        timeSlots.forEach(function (timeSlot) {
            var $row = $('<tr class="time-slot-row"></tr>');

            // 时间段单元格
            var timeRange = timeSlot.startTime + '-' + timeSlot.endTime;
            var $timeCell = $('<td class="time-cell"></td>');
            var timeCellContent = '<div class="time-info">' +
                '<i class="layui-icon layui-icon-time time-icon"></i>' +
                '<span class="time-range">' + timeRange + '</span>' +
                '</div>';
            $timeCell.html(timeCellContent);
            $row.append($timeCell);

            // 为每一天添加单元格
            dateRange.forEach(function (day, dayIndex) {
                var dateStr = formatDate(day, 'YYYY-MM-DD');
                var cellKey = dateStr + '-' + timeSlot.id;

                // 如果单元格已被合并，跳过
                if (mergedCells[cellKey]) {
                    return;
                }

                // 检查该时间段是否在选中的班次时间段内
                var shiftTimeInfo = null;
                var isNextDayPart = false;

                if (selectedShiftTimeMation && selectedShiftTimeMation.length > 0) {
                    for (var i = 0; i < selectedShiftTimeMation.length; i++) {
                        var slot = selectedShiftTimeMation[i];
                        var startSlotId = parseInt(getTimeSlotIdFromTime(slot.startTime));
                        var endSlotId = parseInt(getTimeSlotIdFromTime(slot.endTime));
                        var currentSlotId = parseInt(timeSlot.id);

                        // 检查是否是跨天时间段
                        var isOvernight = endSlotId <= startSlotId;

                        if (isOvernight) {
                            // 第一部分：从开始时间到24:00
                            if (currentSlotId >= startSlotId && currentSlotId <= 48) {
                                shiftTimeInfo = slot;
                                break;
                            }
                            // 第二部分：从00:00到结束时间
                            // 注意：这里修改了判断条件，确保不会超过结束时间
                            if (currentSlotId >= 1 && currentSlotId <= endSlotId) {
                                shiftTimeInfo = slot;
                                isNextDayPart = true;
                                break;
                            }
                        } else {
                            // 普通时间段
                            if (currentSlotId >= startSlotId && currentSlotId < endSlotId) {
                                shiftTimeInfo = slot;
                                break;
                            }
                        }
                    }
                }

                // 如果该时间段在班次时间段内，添加班次信息
                if (shiftTimeInfo) {
                    // 确定是否是起始时间段
                    var isStartTimeSlot = false;
                    if (isNextDayPart) {
                        isStartTimeSlot = timeSlot.id === '1';
                    } else {
                        isStartTimeSlot = getTimeSlotIdFromTime(shiftTimeInfo.startTime) === timeSlot.id;
                    }

                    if (isStartTimeSlot) {
                        // 计算rowspan
                        var rowspan;
                        if (isNextDayPart) {
                            // 第二部分：从00:00到结束时间
                            rowspan = parseInt(getTimeSlotIdFromTime(shiftTimeInfo.endTime)) - 1;
                        } else {
                            // 第一部分：从开始时间到24:00
                            var startId = parseInt(getTimeSlotIdFromTime(shiftTimeInfo.startTime));
                            rowspan = isOvernight ? (48 - startId + 1) : (parseInt(getTimeSlotIdFromTime(shiftTimeInfo.endTime)) - startId);
                        }

                        var $cell = $('<td class="schedule-cell shift-active-cell" data-date="' + dateStr + '" data-time-slot-id="' + timeSlot.id + '" data-day-index="' + day.getDay() + '"></td>');

                        // 设置背景颜色
                        var bgColor = shiftTimeInfo.color || '#e74c3c';
                        $cell.css('background-color', bgColor);

                        if (rowspan > 1) {
                            $cell.attr('rowspan', rowspan);
                            // 记录被合并的单元格
                            for (var i = 1; i < rowspan; i++) {
                                var nextSlotId = parseInt(timeSlot.id) + i;
                                var nextCellKey = dateStr + '-' + nextSlotId;
                                mergedCells[nextCellKey] = true;
                            }
                        }

                        // 添加班次内容
                        var $content = $('<div class="shift-content"></div>');

                        // 添加工位信息
                        renderWorkstationInfo(shiftTimeInfo, $content, isNextDayPart, dateStr);

                        $cell.append($content);
                        $row.append($cell);
                    } else if (!mergedCells[cellKey]) {
                        // 如果不是起始时间段且没有被合并，创建普通单元格
                        var $cell = $('<td class="schedule-cell" data-date="' + dateStr + '" data-time-slot-id="' + timeSlot.id + '" data-day-index="' + day.getDay() + '"></td>');
                        $row.append($cell);
                    }
                } else {
                    // 不在班次时间段内的普通单元格
                    var $cell = $('<td class="schedule-cell" data-date="' + dateStr + '" data-time-slot-id="' + timeSlot.id + '" data-day-index="' + day.getDay() + '"></td>');
                    $row.append($cell);
                }
            });

            $tbody.append($row);
        });

        // 更新表格
        var $table = $('<table class="schedule-table"></table>');
        $table.append($thead).append($tbody);
        $('#scheduleTable').empty().append($table);

        // 更新已排班员工信息
        updateScheduledEmployeesCount();

        // 设置拖放事件
        setupDragEvents();

        // 设置鼠标悬浮事件
        setupHoverEvents();
    }

    // 渲染工位信息
    function renderWorkstationInfo(shiftTimeInfo, $content, isNextDayPart, dateStr) {
        if (shiftTimeInfo.shiftsTimeWorkMation && shiftTimeInfo.shiftsTimeWorkMation.length > 0) {
            // 如果工位数量超过3个，添加滚动容器
            if (shiftTimeInfo.shiftsTimeWorkMation.length > 3) {
                var $workstationContainer = $('<div class="workstation-container"></div>');
                $content.append($workstationContainer);

                // 遍历工位信息
                shiftTimeInfo.shiftsTimeWorkMation.forEach(function (workstation) {
                    var workId = workstation.workId || workstation.id || '';
                    var workName = workstation.workName || workstation.name || '工位' + workId;
                    var minStaff = workstation.minStaff || '0';
                    var maxStaff = workstation.maxStaff || '0';

                    var $workInfo = $('<div class="work-station-info" data-work-id="' + workId + '" data-is-next-day="' + isNextDayPart + '" data-date="' + dateStr + '"></div>');
                    $workInfo.append('<div class="worker-info">' + workName + '</div>');
                    $workInfo.append('<div class="worker-count">最大需求: ' + maxStaff + '</div>');
                    $workInfo.append('<div class="worker-count">最小需求: ' + minStaff + '</div>');
                    $workInfo.append('<div class="worker-count">已排人数: <span class="employee-count">0</span></div>');
                    $workInfo.append('<div class="already-scheduled" style="display:none;">已排员工: 0</div>');

                    $workstationContainer.append($workInfo);
                });
            } else {
                // 如果工位数量不超过3个，保持原有布局
                shiftTimeInfo.shiftsTimeWorkMation.forEach(function (workstation) {
                    var workId = workstation.workId || workstation.id || '';
                    var workName = workstation.workName || workstation.name || '工位' + workId;
                    var minStaff = workstation.minStaff || '0';
                    var maxStaff = workstation.maxStaff || '0';

                    var $workInfo = $('<div class="work-station-info" data-work-id="' + workId + '" data-is-next-day="' + isNextDayPart + '" data-date="' + dateStr + '"></div>');
                    $workInfo.append('<div class="worker-info">' + workName + '</div>');
                    $workInfo.append('<div class="worker-count">最大需求: ' + maxStaff + '</div>');
                    $workInfo.append('<div class="worker-count">最小需求: ' + minStaff + '</div>');
                    $workInfo.append('<div class="worker-count">已排人数: <span class="employee-count">0</span></div>');
                    $workInfo.append('<div class="already-scheduled" style="display:none;">已排员工: 0</div>');

                    $content.append($workInfo);
                });
            }
        } else {
            $content.append('<div class="worker-count">已排人数: 0</div>');
        }
    }

    // 更新已排班员工数量
    function updateScheduledEmployeesCount() {
        // 遍历所有班次单元格
        $('.shift-active-cell').each(function () {
            var $cell = $(this);
            var date = $cell.data('date');
            var timeSlotId = $cell.data('time-slot-id');

            // 查找该单元格对应的班次信息
            var shiftTimeInfo = null;
            if (selectedShiftTimeMation && selectedShiftTimeMation.length > 0) {
                for (var i = 0; i < selectedShiftTimeMation.length; i++) {
                    var slot = selectedShiftTimeMation[i];
                    var startSlotId = parseInt(getTimeSlotIdFromTime(slot.startTime));
                    var endSlotId = parseInt(getTimeSlotIdFromTime(slot.endTime));
                    var currentSlotId = parseInt(timeSlotId);
                    var isOvernight = endSlotId <= startSlotId;

                    if (isOvernight) {
                        if (currentSlotId >= startSlotId || currentSlotId <= endSlotId) {
                            shiftTimeInfo = slot;
                            break;
                        }
                    } else if (currentSlotId >= startSlotId && currentSlotId < endSlotId) {
                        shiftTimeInfo = slot;
                        break;
                    }
                }
            }

            if (!shiftTimeInfo) return;

            // 获取工位信息
            $cell.find('.work-station-info').each(function () {
                var $workstation = $(this);
                var workstationId = $workstation.data('work-id');
                var isNextDay = $workstation.data('is-next-day');
                var workstationDate = $workstation.data('date');

                // 获取该工位的所有排班记录
                var workstationEmployees = scheduleData.filter(function (schedule) {
                    var dateMatch = (schedule.date === workstationDate || schedule.scheduleDate === workstationDate);
                    var workstationMatch = (schedule.workstationId === workstationId ||
                        schedule.farmStationId === workstationId ||
                        schedule.workId === workstationId);

                    // 对于跨天时间段，需要特殊处理
                    if (isOvernight) {
                        if (isNextDay) {
                            // 第二部分：检查00:00到结束时间
                            return dateMatch && workstationMatch &&
                                parseInt(schedule.timeSlotId) <= endSlotId;
                        } else {
                            // 第一部分：检查开始时间到24:00
                            return dateMatch && workstationMatch &&
                                parseInt(schedule.timeSlotId) >= startSlotId;
                        }
                    } else {
                        // 普通时间段
                        return dateMatch && workstationMatch &&
                            parseInt(schedule.timeSlotId) >= startSlotId &&
                            parseInt(schedule.timeSlotId) < endSlotId;
                    }
                });

                // 更新已排班人数
                $workstation.find('.employee-count').text(workstationEmployees.length);
                $workstation.find('.already-scheduled').text('已排员工: ' + workstationEmployees.length);
                $workstation.data('employees', workstationEmployees);

                // 如果是跨天时间段，同步另一部分的工位信息
                if (isOvernight) {
                    var otherPartDate = isNextDay ?
                        getPreviousDay(workstationDate) :
                        getNextDay(workstationDate);

                    // 查找对应的工位
                    $('.work-station-info[data-work-id="' + workstationId + '"][data-date="' + otherPartDate + '"]')
                        .each(function () {
                            var $otherWorkstation = $(this);
                            $otherWorkstation.find('.employee-count').text(workstationEmployees.length);
                            $otherWorkstation.find('.already-scheduled').text('已排员工: ' + workstationEmployees.length);
                            $otherWorkstation.data('employees', workstationEmployees);
                        });
                }
            });
        });
    }

    // 获取下一天的日期
    function getNextDay(dateStr) {
        var date = new Date(dateStr);
        date.setDate(date.getDate() + 1);
        return formatDate(date);
    }

    // 获取前一天的日期
    function getPreviousDay(dateStr) {
        var date = new Date(dateStr);
        date.setDate(date.getDate() - 1);
        return formatDate(date);
    }

    // 获取日期范围
    function getDateRange(start, end) {
        var startDate = new Date(start);
        var endDate = new Date(end);
        var dateArray = [];
        var currentDate = new Date(startDate);

        while (currentDate <= endDate) {
            dateArray.push(new Date(currentDate));
            currentDate.setDate(currentDate.getDate() + 1);
        }

        return dateArray;
    }

    // 获取星期几
    function getDayOfWeek(date) {
        var days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return days[date.getDay()];
    }

    // 格式化日期
    function formatDate(date, format) {
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();

        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;

        if (format === 'YYYY-MM-DD') {
            return year + '-' + month + '-' + day;
        } else if (format === 'MM-DD') {
            return month + '-' + day;
        }

        return year + '-' + month + '-' + day;
    }

    // 初始化拖拽功能
    function initDragAndDrop() {
        // 员工列表项拖拽
        $('.employee-item').each(function () {
            $(this).attr('draggable', 'true');

            this.addEventListener('dragstart', function (e) {
                e.originalEvent.dataTransfer.setData('text/plain', $(this).attr('data-employee'));
                $(this).addClass('dragging');
            });

            this.addEventListener('dragend', function () {
                $(this).removeClass('dragging');
            });
        });

        // 排班表格单元格接收拖拽
        $('.work-station-info').each(function () {
            this.addEventListener('dragover', function (e) {
                e.preventDefault();
                $(this).addClass('dragover');
            });

            this.addEventListener('dragleave', function () {
                $(this).removeClass('dragover');
            });

            this.addEventListener('drop', function (e) {
                e.preventDefault();
                $(this).removeClass('dragover');

                try {
                    var employeeData = JSON.parse(e.originalEvent.dataTransfer.getData('text/plain'));
                    var $cell = $(this).closest('td');
                    var date = $cell.data('date');
                    var timeSlotId = $cell.data('time-slot-id');
                    var dayIndex = $cell.data('day-index');
                    var workstationId = $(this).data('work-id') || '';

                    if (date && timeSlotId) {
                        // 创建一个表示当天的对象
                        var day = {
                            fullDate: date,
                            dayOfWeek: dayIndex
                        };

                        // 调用添加员工到排班表的函数
                        addEmployeeToSchedule(employeeData, day, timeSlotId, workstationId);
                    }
                } catch (error) {
                    console.error("拖放处理错误:", error);
                }
            });
        });
    }

    // 初始化表单事件
    function initFormEvents() {

        // 监听车间选择变化
        form.on('select(workshopSelect)', function (data) {
            workshopId = data.value;
            // 获取员工数据
            fetchEmployeeList();
        });

        // 监听班次选择变化
        form.on('select(shiftSelect)', function (data) {
            shiftId = data.value;

            if (shiftId) {
                handleShiftChange(shiftId);
            } else {
                selectedShiftTimeMation = [];
                renderScheduleTable();
            }
        });

        // 监听员工搜索框
        $('#employeeSearch').on('input', function () {
            var searchText = $(this).val().toLowerCase();

            if (searchText) {
                filteredEmployees = employeeList.filter(function (employee) {
                    var name = employee.staffName ? employee.staffName.toLowerCase() : '';
                    var jobNumber = employee.staffMation && employee.staffMation.jobNumber ? employee.staffMation.jobNumber.toLowerCase() : '';
                    var phone = employee.staffMation && employee.staffMation.phone ? employee.staffMation.phone.toLowerCase() : '';

                    return name.indexOf(searchText) >= 0 || jobNumber.indexOf(searchText) >= 0 || phone.indexOf(searchText) >= 0;
                });
            } else {
                filteredEmployees = [...employeeList];
            }

            renderEmployeeList();
        });

        // 自动排班按钮
        $('#autoSchedule').on('click', function () {
            autoSchedule();
        });

        // 保存排班按钮
        $('#saveSchedule').on('click', function () {
            saveSchedule();
        });

    }

    // 显示班次时间段信息
    function displayShiftTimesInfo() {
        if (!selectedShiftTimeMation || selectedShiftTimeMation.length === 0) {
            $('#shiftTimesInfo').html('<div class="no-data">暂无班次时间段信息</div>');
            return;
        }

        var html = '<div class="shift-times-header">班次时间段:</div>';
        html += '<div class="shift-times-list">';

        selectedShiftTimeMation.forEach(function (timeSlot) {
            var color = timeSlot.color || '#1890ff';
            var borderColor = color;

            // 根据不同的班次ID使用不同的颜色
            if (timeSlot.id === '22' || timeSlot.name === '22') {
                borderColor = '#d44040'; // 红色
            } else if (timeSlot.id === '1' || timeSlot.name === '1') {
                borderColor = '#1cd1a1'; // 绿色
            }

            html += '<div class="shift-time-item" style="border-left: 3px solid ' + borderColor + ';">';
            html += '<div class="shift-time-name">' + (timeSlot.name || timeSlot.id || '未命名时间段') + '</div>';
            html += '<div class="shift-time-range">' + timeSlot.startTime + ' - ' + timeSlot.endTime + '</div>';
            html += '</div>';
        });

        html += '</div>';
        $('#shiftTimesInfo').html(html);
    }

    // 调用初始化函数
    init();

    exports('writeRosterManage', {});

    // 获取工位列表数据
    function fetchWorkstationList(callback) {
        if (!workshopId) {
            console.warn('获取工位列表时workshopId为空');
            if (callback) callback(false, '车间ID不能为空');
            return;
        }

        AjaxPostUtil.request({
            url: sysMainMation.erpBasePath + 'queryFarmStationList',
            params: {
                limit: 10000,
                page: 1,
                farmId: workshopId
            },
            type: 'json',
            method: "POST",
            callback: function (json) {
                if (json.returnCode === 0) {
                    workstationList = json.rows || [];
                    if (callback) callback(true, null, workstationList);
                } else {
                    console.error('获取工位列表失败:', json.msg);
                    if (callback) callback(false, json.msg || '获取工位数据失败');
                }
            },
            errorCallback: function (err) {
                console.error("获取工位列表错误:", err);
                if (callback) callback(false, '获取工位数据失败，请检查网络连接');
            }
        });
    }
});